<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 警告 -->
    <el-alert
      title="注意!只能为第三级分类设置相关参数!"
      type="warning"
      show-icon
      :closable="false"
    >
    </el-alert>
    <!-- 联级选择器分类 -->
    <el-row class="mgY-20">
      <el-col>
        <span>选择商品分类:</span>
        <el-cascader
          v-model="selectedCateId"
          :options="cateList"
          :props="{
            expandTrigger: 'hover',
            label: 'cat_name',
            value: 'cat_id',
          }"
          @change="handleChange"
        ></el-cascader>
      </el-col>
    </el-row>
    <!-- 页标签 -->
    <el-tabs v-model="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="动态参数" name="many">
        <el-button
          type="primary"
          :disabled="selectedCateId.length != 3"
          @click="dialogParamsVisible = true"
          >添加参数</el-button
        >
        <!-- 动态属性表格 -->
        <el-table :data="manyList" style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="scoped">
              <el-tag
                v-for="(val, i) of scoped.row.attr_vals"
                :key="i"
                closable
                :disable-transitions="false"
                @close="closeTag(scoped.row, i)"
                >{{ val }}</el-tag
              >
              <el-input
                class="input-new-tag"
                v-if="scoped.row.inputVisible"
                v-model.trim="scoped.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scoped.row)"
                @blur="handleInputConfirm(scoped.row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scoped.row)"
                >+ New Tag</el-button
              >
            </template>
          </el-table-column>
          <el-table-column type="index"> </el-table-column>
          <el-table-column prop="attr_name" label="属性名称"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scoped">
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="edit(scoped.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="del(scoped.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="静态属性" name="only">
        <el-button
          type="primary"
          :disabled="selectedCateId.length != 3"
          @click="dialogParamsVisible = true"
          >添加属性</el-button
        >
        <!-- 静态属性表格 -->
        <el-table :data="onlyList" style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="scoped">
              <el-tag
                v-for="(val, i) of scoped.row.attr_vals"
                :key="i"
                closable
                :disable-transitions="false"
                @close="closeTag(scoped.row, i)"
                >{{ val }}</el-tag
              >
              <el-input
                class="input-new-tag"
                v-if="scoped.row.inputVisible"
                v-model.trim="scoped.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(scoped.row)"
                @blur="handleInputConfirm(scoped.row)"
                :clearable="true"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(scoped.row)"
                >+ New Tag</el-button
              >
            </template>
          </el-table-column>
          <el-table-column type="index"> </el-table-column>
          <el-table-column prop="attr_name" label="属性名称"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scoped">
              <el-button
                @click="edit(scoped.row)"
                type="primary"
                icon="el-icon-edit"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                @click="del(scoped.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <!--添加属性/参数的对话框  -->
    <el-dialog
      :title="activeName == 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="dialogParamsVisible"
      @close="dialogParamsClose"
    >
      <el-form
        :model="params"
        :rules="paramsRules"
        ref="paramsForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          :label="activeName == 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="params.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑属性对话框 -->
    <el-dialog
      :title="activeName == 'many' ? '编辑动态参数' : '编辑静态属性'"
      :visible.sync="editDialogVisible"
      @close="editDialogClose"
    >
      <el-form
        :model="editParams"
        :rules="paramsRules"
        ref="editParams"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          :label="activeName == 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="editParams.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { confirm } from "../../utils/index";
export default {
  data() {
    return {
      // 编辑属性
      editParams: {
        attr_name: "",
        attr_id: 0,
      },
      editDialogVisible: false,
      // 添加参数的规则
      paramsRules: {
        attr_name: [{ required: true, message: "请输入数据", trigger: "blur" }],
      },
      dialogParamsVisible: false,
      // 添加的参数
      params: {
        attr_name: "",
      },
      // 动态属性列表
      manyList: [],
      // 静态属性列表
      onlyList: [],
      // 选中标签页
      activeName: "many",
      // 以下数据都是为联级选择器的数据
      selectedCateId: [],
      cateList: [],
    };
  },
  methods: {
    //   关闭删除标签
    closeTag(row, i) {
        row.attr_vals.splice(i,1)
        this.saveInput(row)
    },
    showInput(row) {
      row.inputVisible = true;
      //   让文本框自动获得焦点
      // $nextTick方法的作用,就是当页面上元素被重新渲染后,才会指定回调函数中的代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //   离开扩展列的input
     handleInputConfirm(row) {
      row.inputVisible = false;
      //   把写在input中的数据放在对象中
      if (row.inputValue == "") return;
      row.attr_vals.push(row.inputValue);
      this.saveInput(row)
    },
    // 封装上传标签属性的方法
    async saveInput(row) {
      let select = this.selectedCateId;
      let id = select[select.length - 1];
      row.inputValue = "";
      let { data: res } = await this.$axios.put(
        `categories/${id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(),
        }
      );
      if (res.meta.status != 200) return this.$message.error("更新数据失败");
      this.$message.success("更新数据成功");
    },
    //   删除参数
    async del(row) {
      let ret = await confirm().catch((err) => err);
      if (ret == "cancel") return;
      let select = this.selectedCateId;
      let id = select[select.length - 1];
      let { data: res } = await this.$axios.delete(
        `categories/${id}/attributes/${row.attr_id}`
      );
      if (res.meta.status != 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      this.getAttr();
    },
    //   确定编辑分类
    async submitEdit() {
      let select = this.selectedCateId;
      let id = select[select.length - 1];
      let { data: res } = await this.$axios.put(
        `categories/${id}/attributes/${this.editParams.attr_id}`,
        { attr_name: this.editParams.attr_name, attr_sel: this.activeName }
      );
      if (res.meta.status != 200) return this.$message.error("更新数据失败");
      this.$message.success("更新数据成功");
      this.editDialogVisible = false;
      this.getAttr();
    },
    // 点击编辑按钮
    edit(row) {
      this.editParams = {
        attr_id: row.attr_id,
        attr_name: row.attr_name,
      };
      this.editDialogVisible = true;
    },
    //   编辑属性对话框关闭事件
    editDialogClose() {
      this.$refs.editParams.resetFields();
    },
    //   确定提交添加的参数
    async submitParams() {
      let select = this.selectedCateId;
      let id = select[select.length - 1];
      let { data: res } = await this.$axios.post(
        `categories/${id}/attributes`,
        { attr_name: this.params.attr_name, attr_sel: this.activeName }
      );
      if (res.meta.status != 201) return this.$message.error("添加失败");
      this.$message.success("添加成功");
      this.dialogParamsVisible = false;
      this.getAttr();
    },
    //   添加对话关闭
    dialogParamsClose() {
      this.params.attr_name = "";
    },
    //   封装请求相关参数的函数
    async getAttr() {
      let select = this.selectedCateId;
      if (select.length == 3) {
        let id = select[select.length - 1];
        let { data: res } = await this.$axios.get(
          `categories/${id}/attributes`,
          { params: { sel: this.activeName } }
        );
        if (res.meta.status != 200) return this.$message.error("获取数据失败");
        // 处理res.data数据
        res.data.forEach((el) => {
          el.attr_vals
            ? (el.attr_vals = el.attr_vals.split(","))
            : (el.attr_vals = []);
          el.inputVisible = false;
          el.inputValue = "";
        });
        this.activeName == "many"
          ? (this.manyList = res.data)
          : (this.onlyList = res.data);
      }
    },
    // 标签页改变
    handleTabClick() {
      this.getAttr();
    },
    async getCateList() {
      let { data: res } = await this.$axios.get("categories");
      if (res.meta.status != 200) return this.$message.error("获取数据失败");
      this.cateList = res.data;
    },
    // 级联选择器改变
    handleChange() {
      if (this.selectedCateId.length != 3) {
        this.selectedCateId = [];
        this.manyList = [];
        this.onlyList = [];
      } else {
        this.getAttr();
      }
    },
  },
  created() {
    this.getCateList();
  },
};
</script>
<style lang="less" scoped>
.mgY-20 {
  margin: 20px 0;
}
.input-new-tag {
  width: 90px;
}
.el-tag {
  margin: 5px 10px;
}
</style>